package com.datastructures.huffman;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2019/11/814:38
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr={3,44,22,13,12,21,1};
        Node huffmanTree = createHuffmanTree(arr);
        huffmanTree.preOrder();
    }

    public static Node createHuffmanTree(int[] arr){
        //1.将arr的构建成Node集合
        List<Node> nodes=new ArrayList<>();
        for (int value:arr){
            nodes.add(new Node(value));
        }
        //2.从小到达排序
        while (nodes.size()>1){
            Collections.sort(nodes);

            //3.取出权值最小的节点
            Node left=nodes.get(0);
            Node right=nodes.get(1);
            //构建新的二叉树
            Node parentNode=new Node(left.value+right.value);
            parentNode.left=left;
            parentNode.right=right;
            //删除处理过的二叉树
            nodes.remove(left);
            nodes.remove(right);
            //新的二叉树添加到nodes中
            nodes.add(parentNode);
        }

        return nodes.get(0);


    }
}

class Node implements Comparable<Node>{
    /**
     * 节点权值
     */
    int value;

    /**
     * 左子节点
     */

    Node left;
    /**
     * 右子节点
     */
    Node right;

    public Node (int value){
        this.value=value;
    }

    public void preOrder(){
        System.out.println(this);
        if (this.left!=null){
            this.left.preOrder();
        }
        if (this.right!=null){
            this.right.preOrder();
        }
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        //从小到大排序
        return this.value-o.value;
    }
}
